package com.lanxin;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by cyh on 2021/3/17.
 */
public class CustomRealm extends AuthorizingRealm {

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String)authenticationToken.getPrincipal();
        String password = findPasswordByUsername(username);
        if(password!=null){
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,"customrealm");
            authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("lanxin"));
            return authenticationInfo;
        }
        return null;
    }

    public String findPasswordByUsername(String username){
        if("cyh".equals(username)){
            return "11ed6c6d71bfc0a6bdb83f23abad9367";
        }
        return null;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(findRolesByUsername(username));
        authorizationInfo.setStringPermissions(findProessionByUsername(username));

        return authorizationInfo;
    }

    public Set<String> findRolesByUsername(String username){
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("user");
        return roles;
    }
    public Set<String> findProessionByUsername(String username){
        Set<String> pros = new HashSet<>();
        pros.add("user:select");
        pros.add("user:update");
        return pros;
    }

}
